#include "UsbZigbusConnection.h"
#include <QDebug>
#include <qextserialport.h>

UsbZigbusConnection::UsbZigbusConnection(const QString& tty, QObject* parent)
    : AbstractZigbusConnection(parent)
{
    serialPort = NULL;
    this->tty = tty;
}

UsbZigbusConnection::~UsbZigbusConnection()
{
    close();
}

bool UsbZigbusConnection::open()
{
    qDebug() << "[zigbus] initialize connection through " << tty;
    if(tty.isEmpty()) {
        qDebug() << "[zigbus] ERROR: no tty device specified";
        return false;
    }
    serialPort = new QextSerialPort(tty);

    connect(serialPort, SIGNAL(readyRead()), this, SLOT(readAvailableData()));
    if(!serialPort->open(QIODevice::ReadWrite | QIODevice::Text)) {
        qDebug() << "[zigbus] ERROR: cannot open port "<< serialPort->portName();
        return false;
    }
    qDebug() << "[zigbus] Now connected through " << tty;
    return true;
}

void UsbZigbusConnection::close()
{
    qDebug() << "[zigbus] closing connection...";
    if(serialPort != NULL) {
        if(serialPort->isOpen()) serialPort->close();
        delete serialPort;
    }
    qDebug() << "[zigbus] connection closed !";
}

bool UsbZigbusConnection::isOpen() const
{
    return (serialPort && serialPort->isOpen());
}

void UsbZigbusConnection::sendMessage(ZigbusMessage message)
{
    if(!serialPort || !serialPort->isOpen()) {
        qDebug() << "[zigbus] ERROR: unable to send message : port "<<serialPort->portName()<<" not opened !";
        return;
    }
    serialPort->write(message.trame().toLatin1().data());
}

void UsbZigbusConnection::readAvailableData()
{
    QByteArray array = serialPort->readAll();
    qDebug() << "[zigbus] message received : \""<<array<<"\"";
    QString data = array;
    processMessage(data);
}
